package com.apexwear.apexutils.scan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanRecord;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.pm.PackageManager;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.apex.bluetooth.core.EABleBluetoothOption;
import com.apexwear.apexutils.model.BlueInfo;
import com.apexwear.apexutils.model.Device;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class BluetoothScanUtils {
    private final String TAG = this.getClass().getSimpleName();
    private ConcurrentLinkedDeque<Device> deviceList;
    private ScanBluetooth scanCallback;
    private BluetoothManager bluetoothManager;
    private static BluetoothScanUtils eaBleBluetoothScan;
    private volatile boolean isScanning;
    ScanFilterUtils scanFilterUtils;
    volatile boolean isStop;
    Queue<BlueInfo> arrayQueue;
    List<String> addressList;
    ScheduledExecutorService scheduledExecutorService;


    private BluetoothScanUtils() {
        if (scanFilterUtils == null) {
            scanFilterUtils = new ScanFilterUtils();
        }
        arrayQueue = new ConcurrentLinkedDeque<>();
        addressList = new ArrayList<>();
        scheduledExecutorService = Executors.newScheduledThreadPool(1);
        parseBlueData();


    }

    private void parseBlueData() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    if (isStop) {
                        return;
                    }
                    if (arrayQueue != null && !arrayQueue.isEmpty()) {
                        try {
                            BlueInfo blueInfo = arrayQueue.poll();
                            //   Log.e(TAG, "开始解析设备:" + blueInfo.name + ",设备地址:" + blueInfo.address);
                            String sign = scanFilterUtils.isSelfWatch(blueInfo.address, blueInfo.data);
                            if (!TextUtils.isEmpty(sign)) {
                                Device eaBleDevice = new Device();
                                eaBleDevice.setAddressTxt(blueInfo.address);
                                eaBleDevice.setNameTxt(blueInfo.name);
                                eaBleDevice.setTagTxt(sign);
                                deviceList.add(eaBleDevice);
                                /**
                                 if (eaBleDevice != null) {
                                 boolean isExit = false;
                                 for (int i = 0; i < deviceList.size(); i++) {
                                 if (deviceList.get(i) == null) {
                                 continue;
                                 }
                                 if (deviceList.get(i).getAddressTxt().equalsIgnoreCase(eaBleDevice.getAddressTxt())) {
                                 Log.e(TAG, "数据已存在,不再添加,存在的蓝牙地址:" + eaBleDevice.getAddressTxt() + ",存在的蓝牙名:" + eaBleDevice.getNameTxt());
                                 isExit = true;
                                 break;
                                 }
                                 }
                                 if (!isExit) {
                                 deviceList.add(eaBleDevice);
                                 }
                                 }
                                 */
                            } else {
                                Log.e(TAG, "解析数据不存在");
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "解析出现错误:" + e.getMessage());
                        }
                    }

                }
            }, 50, 10, TimeUnit.MILLISECONDS);
        }
    }

    public static BluetoothScanUtils getBluetoothScanInstance() {
        if (eaBleBluetoothScan == null) {
            synchronized (BluetoothScanUtils.class) {
                if (eaBleBluetoothScan == null) {
                    eaBleBluetoothScan = new BluetoothScanUtils();
                }
            }
        }
        return eaBleBluetoothScan;
    }

    public boolean isScanning() {
        return isScanning;
    }

    @SuppressLint("MissingPermission")
    public synchronized void startEABleBluetoothScan() {
        if (isScanning) {
            return;
        }
        isStop = false;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (scanCallback == null) {
            scanCallback = new ScanBluetooth();
        }
        if (!isScanning) {
            BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            if (bluetoothLeScanner != null) {
                if (deviceList == null) {
                    deviceList = new ConcurrentLinkedDeque<>();
                }
                // deviceList.clear();
                isScanning = true;
                List<ScanFilter> filterList = new ArrayList<>();
                filterList.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(EABleBluetoothOption.SERVICE_UUID_8800)).build());
                bluetoothLeScanner.startScan(filterList, new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_BALANCED).build(), scanCallback);
            }
        }
    }

    @SuppressLint("MissingPermission")
    public synchronized void stopScan() {
        isStop = true;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter.isEnabled()) {
            BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            if (bluetoothLeScanner != null) {
                if (scanCallback != null) {
                    bluetoothLeScanner.stopScan(scanCallback);
                }
            }
        }
        isScanning = false;
        scanCallback = null;
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdownNow();
            scheduledExecutorService = null;
        }
        if (arrayQueue != null) {
            arrayQueue.clear();
            arrayQueue = null;
        }
        if (deviceList != null) {
            deviceList.clear();
        }
        deviceList = null;
        if (addressList != null) {
            addressList.clear();
            addressList = null;
        }
        eaBleBluetoothScan = null;
    }

    class ScanBluetooth extends ScanCallback {
        @SuppressLint("MissingPermission")
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BlueInfo blueInfo = new BlueInfo();
            blueInfo.name = result.getDevice().getName();
            blueInfo.address = result.getDevice().getAddress();
            Log.e(TAG, "搜索到的蓝牙地址:" + blueInfo.address);
            if (result.getScanRecord() != null) {
                blueInfo.data = result.getScanRecord().getBytes();
            }
            if (isStop || TextUtils.isEmpty(blueInfo.name) || TextUtils.isEmpty(blueInfo.address)) {
                return;
            }

            if (scanFilterUtils == null) {
                scanFilterUtils = new ScanFilterUtils();
            }
            boolean isE03 = scanFilterUtils.isE03Watch(blueInfo.name);
            if (isE03) {
                return;
            }
            boolean isPolar = scanFilterUtils.isPolar(blueInfo.name);
            if (isPolar) {
                Device eaBleDevice = new Device();
                eaBleDevice.setAddressTxt(blueInfo.address);
                eaBleDevice.setNameTxt(blueInfo.name);
                eaBleDevice.setTagTxt(blueInfo.address);
                eaBleDevice.setPolar(true);
                deviceList.add(eaBleDevice);
                /**
                 if (eaBleDevice != null) {
                 boolean isExit = false;
                 for (int i = 0; i < deviceList.size(); i++) {
                 if (deviceList.get(i) == null) {
                 continue;
                 }
                 if (deviceList.get(i).getAddressTxt().equalsIgnoreCase(eaBleDevice.getAddressTxt())) {
                 isExit = true;
                 break;
                 }
                 }
                 if (!isExit) {
                 deviceList.add(eaBleDevice);
                 }
                 }
                 */
                return;
            }

            if (blueInfo.data != null) {
                if (blueInfo.name.equalsIgnoreCase("FT_38108_CADE")) {
                    Log.e(TAG, "搜索到了" + blueInfo.name + "蓝牙手表,蓝牙地址为:" + blueInfo.address);
                }

                if (isStop) {
                    return;
                }


                if (!addressList.contains(blueInfo.address)) {
                    addressList.add(blueInfo.address);
                    Log.e(TAG, "集合不存在数据,将其加入集合");
                } else {
                    return;
                }
                if (blueInfo.name.contains("iTOUCH AIR 5 PRO")) {
                    Device eaBleDevice = new Device();
                    eaBleDevice.setAddressTxt(blueInfo.address);
                    eaBleDevice.setNameTxt(blueInfo.name);
                    eaBleDevice.setTagTxt(blueInfo.address);
                    eaBleDevice.setPolar(true);
                    deviceList.add(eaBleDevice);
                    return;
                }
                try {
                    arrayQueue.add(blueInfo);
                } catch (Exception e) {
                    Log.e(TAG, "添加信息失败:" + e.getMessage());
                }

            }


        }


        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "扫描失败");

        }
    }

    public List<Device> getDeviceList() {
        if (deviceList != null && !deviceList.isEmpty()) {
            List<Device> dList = new ArrayList<>(deviceList.size());
            for (Device device : deviceList) {
                dList.add(device);
            }
            return dList;
        }
        return null;

    }
}
